const {
  getQuestionBank,
  create,
  deleteMyQuestion,
} = require("../service/question.service");
const path = require("path");
const { deleteQuestionError } = require("../constant/err.type");

class QuestionController {
  async getQuestion(ctx, next) {
    try {
      const res = await getQuestionBank();

      //? ctx.body = `欢迎回来, ${user_name}`;

      if (res) {
        ctx.body = {
          code: 0,
          message: "获取题库成功",
          result: res,
        };
      } else {
        ctx.body = {
          code: 1,
          message: "获取题库失败!",
          result: "",
        };
      }
    } catch (err) {
      console.error("获取题库失败", error);
    }
  }

  async upload(ctx, next) {
    //? console.log(ctx.request.files.file);
    const { file } = ctx.request.files;
    //!console.log(file.type.substring(0, 5)); 校验文件是否为图片
    if (file.type.substring(0, 5) != "image") {
      return ctx.app.emit("error", unSupportedFileType, ctx);
    }
    /*   let file = ctx.request.body.data;
    console.log("body开始---------------------------");
    console.log(ctx.request.body);
    console.log("body结束---------------------------"); */
    /* console.log(path.basename(file.path)); */
    if (file) {
      ctx.body = {
        code: 0,
        message: "图片上传成功",
        result: {
          topic_img: "http://82.157.94.91:8000/" + path.basename(file.path),
        },
      };
    } else {
      return ctx.app.emit("error", fileUploadError, ctx);
    }
  }

  async createQuestion(ctx, next) {
    try {
      const res = await create(ctx.request.body);

      if (res) {
        ctx.body = {
          code: 0,
          message: "创建题目成功",
          result: res,
        };
      } else {
        ctx.body = {
          code: 1,
          message: "创建题目失败!",
          result: "",
        };
      }
    } catch (err) {
      console.error("创建题目失败", error);
    }
  }
  async deleteQuestion(ctx, next) {
    try {
      let id = ctx.request.body.id;

      let res = await deleteMyQuestion(id);
      ctx.body = {
        code: 0,
        message: `删除id为${id}的题目成功`,
        result: res,
      };
    } catch (err) {
      console.log(err);
      return ctx.app.emit("error", deleteQuestionError, ctx);
    }
  }
}

module.exports = new QuestionController();
